package com.linkage.educloud.ah.mvp.presenter;

import com.linkage.educloud.ah.Constants;
import com.linkage.educloud.ah.MyApplication;
import com.linkage.educloud.ah.config.AccountConfig;
import com.linkage.educloud.ah.http.Method;
import com.linkage.educloud.ah.http.RequestUtil;
import com.linkage.educloud.ah.mvp.IBasicView;
import com.linkage.educloud.ah.mvp.contract.IContactDetailPersonalContract;
import com.linkage.educloud.ah.mvp.model.ContactDeatailPersonalModel;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;
import com.zhouyou.http.subsciber.BaseSubscriber;

import org.json.JSONException;
import org.json.JSONObject;

import io.reactivex.Observable;

/**
 * <desc>
 * Created by The Moss on 2018/11/29.
 */

public class ContactDetailPersonalPresenter extends IContactDetailPersonalContract.IPresenter {
    IContactDetailPersonalContract.IModel iModel;

    public ContactDetailPersonalPresenter(IBasicView iView) {
        super(iView);
        iModel = new ContactDeatailPersonalModel();
    }

    @Override
    public void sendInvite(final String userId, final int useType) {
        HttpParams params = RequestUtil.sendInviteInfo(userId, useType);
        Observable observable = iModel.request(Method.POST, true, params);
        observable.compose(iView.bindLifecycle())
                .subscribe(new BaseSubscriber<String>() {
                    @Override
                    public void onError(ApiException e) {
                        ((IContactDetailPersonalContract.IView)iView).onInviteResult(false);
                    }

                    @Override
                    public void onNext(String s) {
                        try {
                            JSONObject json = new JSONObject(s);
                            if (json.getInt("result") == Constants.Result.result){
                                MyApplication.getInstance().getResovler().updateContactInvite(
                                        AccountConfig.getLoginAccount().getLoginAccount(),Long.parseLong(userId),useType,1);
                                ((IContactDetailPersonalContract.IView)iView).onInviteResult(true );
                            }else{
                                ((IContactDetailPersonalContract.IView)iView).onInviteResult(false);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            ((IContactDetailPersonalContract.IView)iView).onInviteResult(false);
                        }
                    }
                });
    }
}
